package cc.telecomdigital.tdstock.activity.groups.monitor.util;

import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.methods.HttpHead;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;

import android.content.Context;
import cc.telecomdigital.tdstock.ITDLApplication;
import cc.telecomdigital.tdstock.Framework.UniqueItem.TDStockLog;

/**
 * 
 * Project：tdstock4
 * Package：cc.telecomdigital.tdstock.activity.groups.monitor.util
 * Class：HttpHelper Description： Creater：hunter
 * [chengpanggang@126.com//hunter@mango.cc] CreateTime：Date：Dec 15, 2011
 * Time：11:42:40 AM Modifier ：hunter [chengpanggang@126.com//hunter@mango.cc]
 * Modify time： Date：Dec 15, 2011 Time：11:42:40 AM Modify Remarks：
 * 
 * @version
 * 
 */
public class HttpHelper
{
	public static final String	TAG					= HttpHelper.class
														.getSimpleName();
	public static final int		TIMEOUT_FOR_CONNECTION	= 8000;
	public static final int		TIMEOUT_FOR_READ		= 10000;
	public static final int		MIN_CONTENT_LENGTH		= 150;					// Length as 144 means
																		// session is expired
	public static final int		DEFAULT_HEAD_CODE		= 0;
	public static final String	DEFALUT_CONTENT_TYPE	= "DEFALUT_CONTENT_TYPE";
	public static final int		DEFALUT_CONTEN_LENGTH	= 0;

	public static String getURLRequestHeadInfo(final String url)
	{
		String info = "";
		try
		{
			DefaultHttpClient client = new DefaultHttpClient();
			HttpParams httpParams = client.getParams();
			HttpConnectionParams.setConnectionTimeout(httpParams,
					TIMEOUT_FOR_CONNECTION);
			HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_FOR_READ);
			client.setParams(httpParams);
			HttpHead httpHead = new HttpHead(url);
			HttpResponse response = client.execute(httpHead);
			String contentType = "";
			String contentLength = "";
			int code;
			StatusLine status = response.getStatusLine();
			code = status.getStatusCode();
			Header header_type = response.getFirstHeader("Content-Type");
			Header header_length = response.getFirstHeader("Content-Length");
			// Header
			// header_content_encoding=response.getFirstHeader("Content-Encoding");
			contentType = header_type.getValue();
			contentLength = header_length.getValue();
			// TDStockLog.e(TAG,
			// header_content_encoding.getValue()==null?"":header_content_encoding.getValue());
			TDStockLog.e(TAG, "contentType:" + contentType);
			TDStockLog.e(TAG, "contentLength:" + contentLength);
			info = code + "&" + contentType + "&" + contentLength;
		}
		catch (Exception e)
		{
			info = DEFAULT_HEAD_CODE + "&" + DEFALUT_CONTENT_TYPE + "&"
					+ DEFALUT_CONTEN_LENGTH;
		}
		return info;
	}

	public static boolean isURLAvailable(String headInfo)
	{
		if (null == headInfo)
		{
			return false;
		}
		try
		{
			String[] temp = headInfo.split("&");
			if ("200".equals(temp[0]))
			{
				return true;
			}
			else
			{
				return false;
			}
		}
		catch (Exception e)
		{
			return false;
		}
	}

	public static boolean isSessionAvaiable(String headInfo)
	{
		if (null == headInfo)
		{
			return false;
		}
		try
		{
			String[] temp = headInfo.split("&");
			if ("text/xml;charset=UTF-8".equals(temp[1]))
			{
				if (Integer.parseInt(temp[2]) > MIN_CONTENT_LENGTH)
				{
					return true;
				}
				else
				{
					return false;
				}
			}
			else
			{
				return true;
			}
		}
		catch (Exception e)
		{
			return false;
		}
	}

	/**
	 * 
	 * @param url
	 *            ready to verfy the rul
	 * @param context
	 * @param num
	 *            //try times
	 * @return the source url if can get valid head info, else null
	 */
	public static String isServerAvaiable(String url, Context context, int num)
	{
		if (null == url || "".equals(url))
		{
			return null;
		}
		TDStockLog.d(TAG, url == null ? "" : "url=" + url);
		String info = getURLRequestHeadInfo(url);
		if (isURLAvailable(info) && isSessionAvaiable(info))
		{
			return url;
		}
		else
		{
			// request new session and upate the url here
			return updateSession(url, context); // just get the new session from
											// context
		}
		/*
		 * TDStockLog.d(TAG, info == null ? "" : "info=" + info); return info;
		 */
	}

	private static String updateSession(final String url, final Context context)
	{

		ITDLApplication app = ((ITDLApplication) context
				.getApplicationContext());
		final String ACCOUNT = "account";
		final String TOKEN = "token";

		StringBuffer buff = new StringBuffer();
		String theUrl = url.trim();
		int paramsPos = theUrl.indexOf("?");
		String uri = theUrl.substring(0, paramsPos == -1 ? theUrl.length()
				: paramsPos); // not including "?"
		String param = "";
		if (paramsPos == -1 || theUrl.endsWith("?"))
		{
			// 没有参数情况
		}
		else
		{
			param = theUrl.substring(paramsPos + 1);
		}

		buff.append(uri);
		buff.append("?");

		String[] pairs = param.split("&");
		for (String pair : pairs)
		{
			String[] paramAndValue = pair.split("=");
			if (paramAndValue.length == 1)
			{
				buff.append(paramAndValue[0]);
				buff.append("=");
				if (ACCOUNT.equals(paramAndValue[0]))
				{
					buff.append(app.getSessionAccount());
				}
				else if (TOKEN.equals(paramAndValue[0]))
				{
					buff.append(app.getSessionToken());
				}
			}
			else if (paramAndValue.length == 2)
			{
				buff.append(paramAndValue[0]);
				buff.append("=");
				if (ACCOUNT.equals(paramAndValue[0]))
				{
					buff.append(app.getSessionAccount());
				}
				else if (TOKEN.equals(paramAndValue[0]))
				{
					buff.append(app.getSessionToken());
				}
				else
				{
					buff.append(paramAndValue[1]);
				}
			}
			buff.append("&");

		}

		buff.deleteCharAt(buff.toString().length() - 1);
		if (buff.toString().indexOf(ACCOUNT + "=") == -1)
		{
			buff.append("&" + ACCOUNT + "=").append(app.getSessionAccount());
		}

		if (buff.toString().indexOf(TOKEN + "=") == -1)
		{
			buff.append("&" + TOKEN + "=").append(app.getSessionToken());
		}

		return buff.toString();
	}

}
